package com.longyi.admin.controller;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.longyi.admin.annotation.Logging;
import com.longyi.admin.entity.RoleMenu;
import com.longyi.admin.entity.User;
import com.longyi.admin.service.MenuService;
import com.longyi.admin.entity.Menu;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.longyi.admin.service.RoleMenuService;
import com.longyi.admin.service.UserService;
import com.longyi.admin.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import com.longyi.admin.common.QueryPageParam;
import com.longyi.admin.common.Result;

/**
* Menu 前端控制器
*
* @author 龙毅
* @since 2025-09-08
*/
@RestController
@RequestMapping("/menu")
public class MenuController {

    // 注入service
    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleMenuService roleMenuService;

    // 统计数量
    @GetMapping("/count")
    public Integer count() {
        return menuService.count();
    }

    // 获取列表
    @GetMapping("/list")
    public List<Menu> list() {
        return menuService.list();
    }

    // 新增数据
    @PostMapping("/save")
    @Logging(record = "新增菜单", type = "新增")
    public Result save(@RequestBody Menu menu) {
        return menuService.save(menu) 
            ? Result.suc(menuService.list().get(menuService.count()-1))
            : Result.fail("新增失败");
    }

    // 修改数据
    @PostMapping("/update")
    @Logging(record = "修改菜单", type = "修改")
    public Result update(@RequestBody Menu menu) {
        return menuService.updateById(menu)
            ? Result.suc("修改成功") 
            : Result.fail("修改失败");
    }

    // 获取详情
    @GetMapping("/info/{id}")
    @Logging(record = "查询菜单详情", type = "查询")
    public Result info(@PathVariable("id") Long id) {
        Menu menu = menuService.getById(id);
        return Result.suc(menu);
    }
    @PostMapping("/modStatus/{id}")
    @Logging(record = "修改菜单状态", type = "修改")
    public Result modStatus(@PathVariable("id") Long id) {
        Menu menu = menuService.getById(id);
        menu.setStatus(menu.getStatus()==1?0:1);
        return menuService.updateById(menu)?Result.suc("修改成功") : Result.fail("修改失败");
    }

    // 批量删除数据
    @Transactional
    @PostMapping("/deleteBatch")
    @Logging(record = "批量删除菜单", type = "删除")
    public Result deleteBatch(@RequestBody Long[] ids) {
        for (Long id : ids){
            List<Menu> list = menuService.lambdaQuery().eq(Menu::getParentId, id).list();
            if (list.size() > 0){
                return Result.fail("请先删除子菜单");
            }else{
                menuService.removeById(id);
                List<RoleMenu> roleMenuList= roleMenuService.lambdaQuery().eq(RoleMenu::getMenuId, id).list();
                roleMenuService.removeByIds(roleMenuList);
            }

        }
//        menuService.removeByIds(Arrays.asList(ids));
        return Result.suc("批量删除成功");
    }

    //批量新增
    @PostMapping("/saveBatch/{perm}/{id}")
    @Logging(record = "批量新增菜单", type = "新增")
    public Result saveBatch(@PathVariable("perm") List<String> perm, @PathVariable("id") Long id) {
        Menu menu=menuService.getById(id);
        if(menu!=null&&menu.getStatus()==1){
            List<Menu> list = menuService.lambdaQuery().eq(Menu::getParentId, id).eq(Menu::getType, 2).list();
            Set<String> names=new HashSet<>(Arrays.asList("新增","修改","删除","查看","控制状态","导入","导出"));
            perm.removeIf(name -> {
                return list.stream().anyMatch(m -> m.getName().equals(name));
            });
            List<Menu> menuList = new ArrayList<>();
            for (String name : perm){
                Menu menu1=new Menu();
                menu1.setParentId(id);
                String code;
                switch ( name){
                    case "新增":
                        code="save";
                        break;
                    case "修改":
                        code="update";
                        break;
                    case "删除":
                        code = "delete";
                        break;
                    case "查询":
                        code = "search";
                        break;
                    case "控制状态":
                        code = "modStatus";
                        break;
                    case "导入":
                        code = "import";
                        break;
                    case "导出":
                        code = "export";
                        break;
                    default:
                        throw new IllegalArgumentException("未知的权限名称: " + name);


                }
                menu1.setName(name);
                menu1.setCode(code);
                menu1.setType(2);
                menu1.setCode(menu.getCode()+'-'+code);
                menuList.add(menu1);
            }
            return menuService.saveBatch(menuList)?Result.suc(menuList):Result.fail("批量新增失败");
        }else
            return Result.fail("菜单不存在或已禁用");

    }
    // 分页查询
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();

        // 提取查询参数
            String id = (String) param.get("id");
            String parentId = (String) param.get("parentId");
            String name = (String) param.get("name");
            String path = (String) param.get("path");
            String code = (String) param.get("code");
            String component = (String) param.get("component");
            String type = (String) param.get("type");
            String icon = (String) param.get("icon");
            String icon3 = (String) param.get("icon3");
            String orderNum = (String) param.get("orderNum");
            String status = (String) param.get("status");

        // 分页配置
        Page<Menu> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Menu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
                    lambdaQueryWrapper.like(Menu::getName, name);
                }
                if (StringUtils.isNotBlank(path) && !"null".equals(path)) {
                    lambdaQueryWrapper.like(Menu::getPath, path);
                }
                if (StringUtils.isNotBlank(code) && !"null".equals(code)) {
                    lambdaQueryWrapper.like(Menu::getCode, code);
                }
                if (StringUtils.isNotBlank(component) && !"null".equals(component)) {
                    lambdaQueryWrapper.like(Menu::getComponent, component);
                }
                if (StringUtils.isNotBlank(type) && !"null".equals(type)) {
                    lambdaQueryWrapper.eq(Menu::getType, type);
                }
                if (StringUtils.isNotBlank(icon) && !"null".equals(icon)) {
                    lambdaQueryWrapper.like(Menu::getIcon, icon);
                }
                if (StringUtils.isNotBlank(icon3) && !"null".equals(icon3)) {
                    lambdaQueryWrapper.like(Menu::getIcon3, icon3);
                }
                if (StringUtils.isNotBlank(orderNum) && !"null".equals(orderNum)) {
                    lambdaQueryWrapper.eq(Menu::getOrderNum, orderNum);
                }
                if (StringUtils.isNotBlank(status) && !"null".equals(status)) {
                    lambdaQueryWrapper.eq(Menu::getStatus, status);
                }

        // 执行分页查询
        IPage result = menuService.PageList(page, lambdaQueryWrapper);
        return Result.suc(result.getTotal(), result.getRecords());
    }
    @PostMapping("/nav")
    public Result nav(@RequestBody User user) {

List<Long> menuIds=getMenuIds(user);
        List<Menu> navs=menuService.getUserMenu(user,menuIds);
       List<String> perm=new ArrayList<>();
       for (Long menuId:menuIds){
           perm.add(menuService.getById(menuId).getCode());
       }
       HashMap map=new HashMap();
       map.put("navs", navs);
       map.put("perm", perm);
       return Result.suc(map);
    }
    public List<Long> getMenuIds(User user) {
        List<Long> menuIds=userService.getMenuIds(user.getRole());
        Set menuSet=new HashSet<>();
        for (Long menuId:menuIds){
            Menu menu=menuService.getById(menuId);
            if(menu.getType()==2){
                menuSet.add(menuId);
                menuSet.add(menu.getParentId());
                Menu menu2=menuService.getById(menu.getParentId());
                if(menu2.getType()==1&&menu2.getParentId()!=0){
                    menuSet.add(menu2.getParentId());
                }
            }else
                menuSet.add(menuId);


        }
        return new ArrayList<>(menuSet);
    }
    //获取菜单树
    @GetMapping("/tree")
    public Result tree() {
        List<Menu> list = menuService.tree(menuService.lambdaQuery().orderByAsc(Menu::getOrderNum).list());
        return Result.suc(list);
    }
    //获取菜单id
    @GetMapping("/ids")
    public Result ids() {
        List<Long> list = menuService.list().stream().map(p->p.getId()).collect(Collectors.toList());
        return Result.suc(list);
    }
}